package Demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Test2 {
    private static int count = 0;
    public static void main(String[] args) {
        ReentrantLock locker = new ReentrantLock(true);

        Thread t1 = new Thread( () -> {
          if (locker.tryLock()) {
              try {
                  for (int i = 0; i < 50000; i++) {
                      count++;
                  }
              } finally {
                  locker.unlock();
              }
          } else {
              System.out.println("获取锁失败");
          }
        });

        Thread t2 = new Thread( () -> {
            try {
                if (locker.tryLock(1, TimeUnit.SECONDS)) {
                    try {
                        for (int i = 0; i < 50000; i++) {
                                count++;
                        }
                    } finally {
                        locker.unlock();
                    }
                } else {
                    System.out.println("获取锁超时");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);


    }
}
